package 链表;

import common.ListNode;

/**
 * @author tmh
 * @date 2024/9/23 19:22
 * @description
 */
public class T25K个一组翻转链表 {
    public static void main(String[] args) {
        ListNode head =new ListNode(1,new ListNode(2,new ListNode(3,new ListNode(4,new ListNode(5)))));
        reverseKGroup(head,2);
    }

    public static ListNode reverseKGroup(ListNode head, int k) {

        ListNode tail = head;
        //判断有没有k个节点
        for (int i = 1; i <= k; i++) {
            if (tail == null) {
                return head;
            }
            tail = tail.next;
        }
        //翻转
        ListNode newHead = reverse(head, tail);
        head.next=reverseKGroup(tail,k);
        return newHead;
    }

    private static ListNode reverse(ListNode head, ListNode tail) {
        ListNode pos1 = new ListNode(), pos2 = new ListNode();
        while (head != tail) {
            //保存head的下一个节点
            pos2=head.next;
            head.next=pos1;
            pos1=head;
            head=pos2;
        }
        return pos1;
    }
}
